from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from utils.tooljwt import tooljwt
from django.contrib.auth.models import User
from user import models

class JWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 从请求头中获取 Authorization 字段
        auth = request.META.get('HTTP_AUTHORIZATION', None)
        # print(auth)
        # if auth is not None:
        #     user= tooljwt.checktoken(auth)
        #     if user['id'] is not None:
        #         userdata=models.UserModels.objects.filter(id=user['id']).first()
        #         return userdata
        # else:
        #     return None
        # 检查 Authorization 字段的格式（例如 Bearer <token>）
        if auth is not None:
            auth_parts = auth.split()
            if len(auth_parts) == 2 and auth_parts[0].lower() == 'bearer':
                token = auth_parts[1]
                user = tooljwt.checktoken(token)
                if user:
                    userdata=models.UserModel.objects.get(id=user.get("userid"))
                    return userdata, None
                # if user:
                #     # 根据 user_id 获取用户对象
                #     userdata = models.UserModel.objects.filter(id=user['userid']).first()
                #     print(userdata)
                #     return "123"  # 返回用户和 None（因为没有认证后端）

        # 如果 token 无效或不存在，则返回 None（表示认证失败）
        #return None

    def authenticate_header(self, request):
        return 'Bearer realm="api"'